Chapter 16: Exercises

  1. What are the loop commands provided by MATLAB?

  2. Use of for-loop: What is the purpose of the following script? a=magic(5); for i = a disp(norm(i)^2); end

  3. Use of continue: Consider the following script: x = [1 -2 3 -4 5 0 2]; total = 0; for i = 1:length(x) if x(i)<0, continue; end total=total+x(i); end
    1. What is the purpose of the script? What is the final value of "total"?
    2. Can you rewrite the script using the while-loop instead?

  4. Use of while: Consider the following script: n = 1; while prod(1:n) < 1e100 n = n+1 end fprintf('%g! = %e > 1e100\n', n, prod(1:n));
    1. What is the purpose of the script?
    2. Can you rewrite the script using the for-loop instead?
    3. Can you make it more efficient by not computing the product all over again?
  5. How many times will this script prints "Hello"? for i=-1:-2:-50 fprintf('Hello\n'); end
  6. 下列 MATLAB 程式執行完後,請問顯示的結果是? x = zeros(3); for i = 1:2:9 x(i) = i^2; end x
    Ans: x = 1 0 49 0 25 0 9 0 81
  7. 下列 MATLAB 程式執行完後,請問顯示的結果是? h = zeros(3); for i=1:3 for j=1:3 h(i,j)=i*j/(i^2+j^2); end end format rat h
    Ans: h = 1/2 2/5 3/10 2/5 1/2 6/13 3/10 6/13 1/2
  8. 下列 MATLAB 程式執行完後,請問變數 total 的值是? i=1; x = [1 2 3 4 0 -1 -2 -3 4]; total = 0; while(x(i)) total=total+x(i); i=i+1; end
    Ans: 10
  9. 給定一向量 A,請寫一段程式 useIf01.m,利用 if-then-else 指令來依元素值不同 而印出不同訊息。舉例而言,當 A=[-1, 1, 0, 2+i] 時,你的程式碼應印出:
    • A(1) = -1 是負數
    • A(2) = 1 是正數
    • A(3) = 0 是零
    • A(4) = 2+i 是複數
    請用下列 A 來測試你的程式,並將結果印出來: A = randn(20,1)+(rand(20,1)>0.7)*sqrt(-1);
  10. 重複上一題,程式碼名稱為 useSwitch01.m,但是必須使用 switch-case-otherwise 指令來完成。

MATLAB程式設計:入門篇